<?php

uses('sanitize');

class ProductsController extends AppController {

	var $name = 'Products';
	var $helpers = array('Html', 'Form', 'Cache', 'Ajax');
	var $components = array('Acl', 'Security');

	function beforeFilter()
	{
		$this->Security->requirePost('category_list');
		$this->Security->requireAuth('delete');
		$this->Security->blackHoleCallback = 'invalid';
		if($this->Acl->check($this->Session->read('user'), '/products/add')){
			$this->set('showAdmin', TRUE);
		}else{
			$this->set('showAdmin', FALSE);
		}
	}
	
	function invalid()
	{
		header ('HTTP/x 400 Bad Request');
		echo('<h1>Upward</h1>');
		echo('<p>Nous sommes désolé - Un problème est servenue, merci de renvoyer le formulaire une nouvelle fois.</p>');
		die;
	}

//actions customers
	function index() {
		$this->Product->recursive = 0;	
		$this->set('products', $this->Product->findAll(null, null, 'Product.title ASC'));
			
		/*load a different layout depending on the accepted content*/
	/*	if($this->RequestHandler->accepts('html')) {
			/*already using html template */
	/*		if($this->RequestHandler->accepts('rss')) {
				/*include rss link*/
			/*	$this->set('feed_ressource', '/products');
			}
		} elseif($this->RequestHandler->accepts('rss')) {
			/*only rss feed*/
		/*	$this->layout = 'rss';
		}*/
	}

	function view($id = null) {
		if(!$id) {
			$this->Session->setFlash('Invalid id for Product.');
			$this->redirect('/product/index');
		}
		$product = $this->Product->read(null, $id);
		//###########
		//begin test preg tinyMCE
		//###########
		
		//###########
		//end test preg tinyMCE
		//###########
		$this->set('product', $product);		
	}

	//product formulaire to add session var : basket
	function addToBasket(){
		if(!$this->Session->read('user')){
			$this->Session->setFlash('Connexion requise');
			$this->redirect('/users/index');
		}else{
			$product_present = false;

			//if edited basket
			if($this->Session->read('basket')){
				$ar_products =  $this->Session->read('basket');
	
				//if product is already present in the basket session var add only quantity
				foreach($ar_products as $product_key => $ar_product){
					if($ar_product['id'] == $this->data['Product']['Product_id']){
						$key = $product_key;
						$product_present = true;
						break;
					}
				}
			}
		
			if($product_present){
				$ar_products[$product_key]['quantity'] = $ar_products[$key]['quantity']+$this->data['Product']['Quantity'];
			}else{
				//show product only
				$this->Product->recursive = 0;
				$product = $this->Product->read(null, $this->data['Product']['Product_id']);
			
				$product['Product']['quantity'] = $this->data['Product']['Quantity'];
				$ar_products[] = $product['Product'];
			}
	
			$this->Session->write('basket', $ar_products);	
			$this->redirect('/customers/mybasket');
		}
	}

//actions dealers
	//ajax - category/ajaxadd.thtml POST
	function category_list(){
		$this->set('categories', $this->Product->Category->generateList(null, 'title ASC'));
		$this->render('category_list', 'ajax');
	}

	function add() {
		$username = $this->Session->read('user');
		if(!$this->Acl->check($this->Session->read('user'), '/products/add', '*')){
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/products/index');
		}else{
			if(empty($this->data)) {
				$this->set('categories', $this->Product->Category->generateList());
				$this->render();
			} else {
				$san = new Sanitize();	
				$this->data['Product']['title'] = $san->paranoid($this->data['Product']['title'], array(' ', '.', '+', '-', '_', ':'));
				$this->data['Product']['description'] = $san->sql($this->data['Product']['description']);
				$this->data['Product']['picture'] = $san->paranoid($this->data['Product']['picture'], array('.', '/', ':', '-', '+', '_'));
				
				$category_id = $this->data['Product']['category_id'];
							 
				$this->cleanUpFields();
				if($this->Product->save($this->data)) {
					$product_id = $this->Product->id;
					$product_alias = 'product-'.$product_id;
				
					$aco = new Aco();
					$aco->create($product_id, $category_id, $product_alias);
					$this->Acl->allow('dealers', $product_alias, '*');
					$this->Acl->deny('dealers', $product_alias, 'delete');
					$this->Acl->allow('admins', $product_alias, '*');

					$this->Session->setFlash('Le produit a été enregistré.');
					$this->redirect('/products/index');
				} else {
					$this->Session->setFlash('Merci de corriger les erreurs suivantes.');
					$this->set('categories', $this->Product->Category->generateList());
				}
			}
		}
	}

	function edit($id = null) {
		if(!$id) {
			$this->Session->setFlash('Id invalide dans les produits.');
			$this->redirect('/products/index');
		}
		if(!$this->Acl->check($this->Session->read('user'), 'product-'.$id, 'update')){
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/products/index');
		}else{
			if(empty($this->data)) {
				$this->data = $this->Product->read(null, $id);
				$this->set('categories', $this->Product->Category->generateList());
			} else {
				$san = new Sanitize();	
				$this->data['Product']['title'] = $san->paranoid($this->data['Product']['title'], array(' ', '.', '+', '-', '_', ':'));
				$this->data['Product']['description'] = $san->sql($this->data['Product']['description']);
				$this->data['Product']['picture'] = $san->paranoid($this->data['Product']['picture'], array('.', '/', ':', '-', '+', '_'));
		
				$this->cleanUpFields();
				if($this->Product->save($this->data)) {
					$this->Session->setFlash('Le produit a été mise à jour.');
					$this->redirect('/products/index');
				} else {
					$this->Session->setFlash('Merci de corriger les erreurs suivantes.');
					$this->set('categories', $this->Product->Category->generateList());
				}
			}
		}
	}


//actions admins
	function delete($id) {
		if(!$this->Acl->check($this->Session->read('user'), 'product-'.$id, 'delete')){
			$this->Session->setFlash('Action non autorisée');
			$this->redirect('/products/index');
		}else{
			if($this->Product->del($id))
			{
				$aco = new Aco();
				$aco->delete('product-'.$id);
				
				$this->Session->setFlash('Le produit a été effacé : id '.$id.'');
				$this->redirect('/products/index');
			}
		}
	}
	
}
?>